import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import IResponse from '@/services/response.service';
import axios, { RawAxiosRequestHeaders } from 'axios';
import { defer, of, catchError, map, concatMap, forkJoin, Observable, retry } from 'rxjs';
import { DyUploadAuth, DyUploadPart, DyUploadRequestNode, DyUploadTask } from '@/modules/dy/dy.typing';
import DyHelper, { DyHelperRequest } from '@/modules/dy/dy.helper';
import * as cryptoJs from 'crypto-js';
import * as crypto from 'crypto';
import * as path from 'path';
import * as fs from 'fs-extra';
import { debug } from '@/modules/dy/dy-s2';
import IHelper from '@/services/helper.service';


@Injectable()
export class DyService {
  test(): any {
    let serviceName = 'vod';
    const payload = {
      'request': {
        'method': 'POST',
        'url': 'https://vod.bytedanceapi.com/?Action=CommitUploadInner&Version=2020-11-19&SpaceName=aweme&app_id=2906&user_id=572219949591661',
        'timeout': 30000,
        'region': 'cn-north-1',
        'params': {
          'Action': 'CommitUploadInner',
          'Version': '2020-11-19',
          'SpaceName': 'aweme',
          'app_id': 2906,
          'user_id': '572219949591661',
        },
        'headers': {},
        'pathname': '/',
        'custom': '{"SessionKey":"eyJhY2NvdW50VHlwZSI6InNwYWNlIiwiZW5jcnlwdEtleSI6IiIsImVuY3J5cHRNb2RlIjoiIiwiZXh0cmEiOiJlZGdlX25vZGU9YWdzeHhhXHUwMDI2ZmlsZV9zaXplPTE0NDA0NDk3LjAwMDAwMFx1MDAyNmhvc3Q9dG9zLWFnc3h4YS1jdC5kb3V5aW4uY29tXHUwMDI2cHJvdmluY2U9U2hhYW54aVx1MDAyNnJlZ2lvbj1DTlx1MDAyNnN0cmF0ZWd5PWxvbmdfbWVtb3J5X2ZpbHRlcl92M1x1MDAyNnRlZGR5X2VkZ2VfaG9zdD10b3MtYWdzeHhhLWN0LmRvdXlpbi5jb21cdTAwMjZ1cGxvYWRfbW9kZT1zZXJpYWxcdTAwMjZ1c2VyX2lwPTIyMi45MS4xMjYuMjMwXHUwMDI2dmlkYz1obFx1MDAyNnZ0cz0xNzA1NTY5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BkMmxhVnpWcVkyNXNkMlJHT1doaVIyUjJTV3B2YVVscGQybGFWelZxWTI1c2QyUkdPWEphV0d0cFQybEphVXhEU25walIwWnFXbE5KTmtsdFJqTmFWekZzU1dsM2FXUkhPWHBZTWpGc1pFZEZhVTlwU2pkWVEwcFdWVEJXVTFnd2JFVllRMGsyV0VOSk1VNTZTWGxOVkdzMVRrUnJNVTlVUlRKT2FrWmpTVzR3YVdaWU1Ua3VSamR2ZWxaVGFtbzRORmhhUTBGc1pHZFhOelZoU1V0UVpVaHJVVFZCZEVGNWRFSnhNVkYyYzNSeVZTSjk6YTRkYzIyZmEyN2QwMTBlYzI0OGQ5NmQ4N2JkODlkZmUxZjg3Y2Q3N2MwNTQ4NTgxYjAzMzU3NGZhZDBhYmMwNiIsInRvcERvbWFpbiI6InZvZC5ieXRlZGFuY2VhcGkuY29tIiwidXJpIjoidG9zLWFnc3h4YS12LTAwMDAvb2dBOHd2UWdEb0E4b0RPMVZmOW5jcWJ6ZXZuZEFCMlJCQTlsWVIiLCJ1c2VJc3BTY2hlZHVsaW5nIjoiZmFsc2UiLCJ2aWQiOiJ2MDMwMGZnMTAwMDBjbWtlbnJyYzc3dTczMzdzMHB0MCJ9',
          'Functions': [{ 'name': 'GetMeta' }, { 'name': 'Snapshot', 'input': { 'SnapshotTime': 0 } }],
        },
      },
      'e': {
        'accessKeyId': 'AKTPOGI1MmRiNDQzYzZiNGRjYzhjZmJhYjBjYWE5NGM0ZWU',
        'secretAccessKey': 'TlAjBakBgMVatfOWR6GWZMEPeLk6FlIOKW08VrV9xJxo51X9FBuSzO58c691eQ/Y',
        'sessionToken': 'STS2eyJMVEFjY2Vzc0tleUlEIjoiQUtMVFlqZGpZVFV3WldRd1pEVTBORFJtTW1Fd05XVTVObUUxTVRkaVl6VXlaVGciLCJBY2Nlc3NLZXlJRCI6IkFLVFBPR0kxTW1SaU5EUXpZelppTkdSall6aGpabUpoWWpCallXRTVOR00wWldVIiwiU2lnbmVkU2VjcmV0QW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ceName': 'vod',
    };
    payload.request.custom = '';
    const helper = new DyHelper(payload.request, payload.serviceName);
    return {
      me: helper.addAuthorization(payload.e, payload.n),
      result: {
        'X-Amz-Date': '20240118T091426Z',
        'x-amz-security-token': 'STS2eyJMVEFjY2Vzc0tleUlEIjoiQUtMVFlqZGpZVFV3WldRd1pEVTBORFJtTW1Fd05XVTVObUUxTVRkaVl6VXlaVGciLCJBY2Nlc3NLZXlJRCI6IkFLVFBPR0kxTW1SaU5EUXpZelppTkdSall6aGpabUpoWWpCallXRTVOR00wWldVIiwiU2lnbmVkU2VjcmV0QWNjZXNzS2V5IjoiaThQQ3poYTY0V1Z2ZmNIYmcvL3UrZmJ5cmgyZnY1YWk0YmQ1TnNIK0ZUSTFVOWdpR2pmYmRaNWZ4SVNVa0VOaEdYN1hncm42VTgxa2ZIaTYrem12UHNrY1hJOFc0NElMdjBNZlMrOEF6VWM9IiwiRXhwaXJlZFRpbWUiOjE3MDU3NDIwNjIsIlBvbGljeVN0cmluZyI6IntcIlN0YXRlbWVudFwiOlt7XCJFZmZlY3RcIjpcIkFsbG93XCIsXCJBY3Rpb25cIjpbXCJ2b2Q6KlwiLFwiSW1hZ2VYOipcIl0sXCJSZXNvdXJjZVwiOltcIipcIl19LHtcIkVmZmVjdFwiOlwiQWxsb3dcIixcIkFjdGlvblwiOltcIlVzZXJJZFwiXSxcIlJlc291cmNlXCI6W1wiNTcyMjE5OTQ5NTkxNjYxXCJdfSx7XCJFZmZlY3RcIjpcIkFsbG93XCIsXCJBY3Rpb25cIjpbXCJBcHBJZFwiXSxcIlJlc291cmNlXCI6W1wiMTEyOFwiXX0se1wiRWZmZWN0XCI6XCJBbGxvd1wiLFwiQWN0aW9uXCI6W1wiVXNlclJlZmVyZW5jZVwiXSxcIlJlc291cmNlXCI6W1wie1xcXCJwc21cXFwiOlxcXCJkb3V5aW4uY3JlYXRvci5jb250ZW50XFxcIn1cIl19LHtcIkVmZmVjdFwiOlwiQWxsb3dcIixcIkFjdGlvblwiOltcIlNlc3Npb25DaGVja1wiXSxcIlJlc291cmNlXCI6W1wiVWlkXCJdfSx7XCJFZmZlY3RcIjpcIkFsbG93XCIsXCJBY3Rpb25cIjpbXCJQU01cIl0sXCJSZXNvdXJjZVwiOltcImRvdXlpbi5jcmVhdG9yLmNvbnRlbnRcIl19XX0iLCJTaWduYXR1cmUiOiIyZTk3YzkwMGE2ZGNlYzJjNDI0NWFhMTE5ZjkwZmVhZWQ1YzJmYWNjOWU5YmZlZWQ1ZDgxZjAwNjEyZjIxYzUzIn0=',
        'X-Amz-Content-Sha256': '9cc1969478569550c95886e01ded1f2d808efe6de248a8bbb39d57571d7d10f7',
        'Authorization': 'AWS4-HMAC-SHA256 Credential=AKTPOGI1MmRiNDQzYzZiNGRjYzhjZmJhYjBjYWE5NGM0ZWU/20240118/cn-north-1/vod/aws4_request, SignedHeaders=x-amz-content-sha256;x-amz-date;x-amz-security-token, Signature=9ffb90a012250d30bff1e6bf89d72029f024a0d67a8f4d9f2a03b3b63e665fe5',
      },
    };
  }

  publish(opt: { videoFile: Express.Multer.File, coverFile: Express.Multer.File, config: any }) {
    const task: DyUploadTask = {
      videoFile: opt.videoFile,
      coverFile: opt.coverFile,
      config: opt.config,
    };
    return this.buildPubTitleConfig(task)
    return this.uploadVideo_requestAuth(task).pipe(
      concatMap(() => this.uploadVideo_applyUploadInner(task)),
      concatMap(() => this.uploadVideo_uploadFullVideo(task)),
      concatMap(() => this.uploadVideo_commitUploadInner(task)),
      concatMap(() => this.uploadCover(task)),
      concatMap(() => this.publishTask(task)),
      map(() => {
        const { coverFile, videoFile, ...rest } = task;
        return rest;
      }),
    );
  }

  uploadVideo_requestAuth(task: DyUploadTask) {
    const uri: string = `https://creator.douyin.com/web/api/media/upload/auth/v5/`;
    const params = {
      // "cookie_enabled": "true",
      // "screen_width": "1920",
      // "screen_height": "1080",
      // "browser_language": "zh-CN",
      // "browser_platform": "MacIntel",
      // "browser_name": "Mozilla",
      // "browser_version": "5.0+(Macintosh;+Intel+Mac+OS+X+10_15_7)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/120.0.0.0+Safari/537.36",
      // "browser_online": "true",
      'timezone_name': 'Asia/Shanghai',
      // "aid": "1128",
      // "msToken": "R_OQjLCGLoSo-xshlS4o-Rk-VeWFuk2avD9yITqKXCdjqtyyTySbtd-Gde7AaZN3a7BopTLsIYyd3O4_byW5LY893P4bmv_FUgzaYjVUjvMt24j9z6oJhA",
      // "a_bogus": "QvBmhO20Msm13D3eahkz9CXmFPg0YW4hgZEPHtIL8zwo",
      // "X-Bogus": "DFSzsdVuzEUANSvEti/BOORXoR0n",
      // "_signature": "_02B4Z6wo00001PUiGYAAAIDBGwfdf0wiKZD1Jh0AAFj13dDx8hkj1cBWUbFE4qcD1Nuq-HcMA8A4jFz9O-HA2HJmyFtMrbsAvTAc2ZL-AAfKu9Og6bdYLgcxaJ9wgFZaTWE87HPJU3znYphh81"
    };
    const headers: RawAxiosRequestHeaders = {
      'Host': 'creator.douyin.com',
      'Cookie': 'bd_ticket_guard_client_web_domain=2; passport_csrf_token=8ac577ac5cad0f1a486aaad9e00cb304; passport_csrf_token_default=8ac577ac5cad0f1a486aaad9e00cb304; stream_recommend_feed_params=%22%7B%5C%22cookie_enabled%5C%22%3Atrue%2C%5C%22screen_width%5C%22%3A1920%2C%5C%22screen_height%5C%22%3A1080%2C%5C%22browser_online%5C%22%3Atrue%2C%5C%22cpu_core_num%5C%22%3A12%2C%5C%22device_memory%5C%22%3A8%2C%5C%22downlink%5C%22%3A10%2C%5C%22effective_type%5C%22%3A%5C%224g%5C%22%2C%5C%22round_trip_time%5C%22%3A50%7D%22; volume_info=%7B%22isUserMute%22%3Afalse%2C%22isMute%22%3Atrue%2C%22volume%22%3A0.6%7D; strategyABtestKey=%221705463377.324%22; home_can_add_dy_2_desktop=%221%22; FORCE_LOGIN=%7B%22videoConsumedRemainSeconds%22%3A180%2C%22isForcePopClose%22%3A1%7D; IsDouyinActive=false; stream_player_status_params=%22%7B%5C%22is_auto_play%5C%22%3A0%2C%5C%22is_full_screen%5C%22%3A0%2C%5C%22is_full_webscreen%5C%22%3A0%2C%5C%22is_mute%5C%22%3A1%2C%5C%22is_speed%5C%22%3A1%2C%5C%22is_visible%5C%22%3A0%7D%22; _tea_utm_cache_2906=undefined; s_v_web_id=lrh8v340_Iufk7QSy_PJYo_4gxu_AfOa_cmHysRjcmWmL; pwa2=%220%7C0%7C1%7C0%22; passport_assist_user=CkDljygontbPJ87N3y9FkFKscatGwjQQgs04KqiBZW3LqVs4tJ00j5WCW4ysoht6fiZl8M1pI7GenqL49FkrR6r4GkoKPPE4ePu6muJXDD1HJyHNHM_T7dq2kxpAFL5wiOVx9-vPD14wZH2UzXwb3aGBBeph_AqB_sQvDgYWNY4mDhCP8cYNGImv1lQgASIBAzYfpV4%3D; n_mh=CVCcgMkWFJlJavMf5K1rAr0kZbZmZbXiNogVcvAYS14; sso_uid_tt=d9899fd058f37229c87972a34759ed1f; sso_uid_tt_ss=d9899fd058f37229c87972a34759ed1f; toutiao_sso_user=9aa743193ce0358c5e33412736b210e0; toutiao_sso_user_ss=9aa743193ce0358c5e33412736b210e0; sid_ucp_sso_v1=1.0.0-KDI5ZmFmMTJiZmUyY2EzYzlkMGNlZDcwNzY1NmU1OGUxNzRiYTgyZGEKHwjt2NC25Y2CARCEnp2tBhjaFiAMMJHalY8GOAZA9AcaAmxxIiA5YWE3NDMxOTNjZTAzNThjNWUzMzQxMjczNmIyMTBlMA; ssid_ucp_sso_v1=1.0.0-KDI5ZmFmMTJiZmUyY2EzYzlkMGNlZDcwNzY1NmU1OGUxNzRiYTgyZGEKHwjt2NC25Y2CARCEnp2tBhjaFiAMMJHalY8GOAZA9AcaAmxxIiA5YWE3NDMxOTNjZTAzNThjNWUzMzQxMjczNmIyMTBlMA; passport_auth_status=55a0f2bab99008a835be7481fa43d207%2C; passport_auth_status_ss=55a0f2bab99008a835be7481fa43d207%2C; uid_tt=15ac3dcdb321c6dcafd58d4f27cfaaf5; uid_tt_ss=15ac3dcdb321c6dcafd58d4f27cfaaf5; sid_tt=380ada5aa45d24dd94617759cca38f45; sessionid=380ada5aa45d24dd94617759cca38f45; sessionid_ss=380ada5aa45d24dd94617759cca38f45; csrf_session_id=80aae493eb9e20f3d60070094d4f6ace; ttwid=1%7Co95Gjgo8evGWkYs0q1d0-pZsGAh_1ET-tzwv5V7NhoE%7C1705463558%7Cd091d76f66e99e0298737808a9646bff1413421fd6810bee3d930493eac877a6; oc_login_type=LOGIN_PERSON; _bd_ticket_crypt_doamin=2; _bd_ticket_crypt_cookie=1ba2128c644dcc42f2439e82d22a5794; __security_server_data_status=1; bd_ticket_guard_client_data=eyJiZC10aWNrZXQtZ3VhcmQtdmVyc2lvbiI6MiwiYmQtdGlja2V0LWd1YXJkLWl0ZXJhdGlvbi12ZXJzaW9uIjoxLCJiZC10aWNrZXQtZ3VhcmQtcmVlLXB1YmxpYy1rZXkiOiJCRlpNMTBtQk03REoyaGtIOG1DQjhYNXdtMkZKSEthRXpBclI1TGpseCtyRXVvZTliL3pBcTdrRFRmMHhDbUIxaVZCK1lmSytiVFp0MXlQNDgxNWZ6dXM9IiwiYmQtdGlja2V0LWd1YXJkLXdlYi12ZXJzaW9uIjoxfQ%3D%3D; passport_fe_beating_status=true; sid_guard=380ada5aa45d24dd94617759cca38f45%7C1705463559%7C5183999%7CSun%2C+17-Mar-2024+03%3A52%3A38+GMT; sid_ucp_v1=1.0.0-KDhjMDY0YjY4YThkODVkYWY3YjgzM2IxMGZhYTA1N2RhYjllNzNkZmEKGwjt2NC25Y2CARCHnp2tBhjaFiAMOAZA9AdIBBoCbGYiIDM4MGFkYTVhYTQ1ZDI0ZGQ5NDYxNzc1OWNjYTM4ZjQ1; ssid_ucp_v1=1.0.0-KDhjMDY0YjY4YThkODVkYWY3YjgzM2IxMGZhYTA1N2RhYjllNzNkZmEKGwjt2NC25Y2CARCHnp2tBhjaFiAMOAZA9AdIBBoCbGYiIDM4MGFkYTVhYTQ1ZDI0ZGQ5NDYxNzc1OWNjYTM4ZjQ1; msToken=R_OQjLCGLoSo-xshlS4o-Rk-VeWFuk2avD9yITqKXCdjqtyyTySbtd-Gde7AaZN3a7BopTLsIYyd3O4_byW5LY893P4bmv_FUgzaYjVUjvMt24j9z6oJhA==; tt_scid=RgVlmF4BgErD-VN4WJOSAaZrR6YmWHxXMJFoUFr1YWhdikzYhEI2zsXwydiqYhCl13f5; odin_tt=a22f2d8ef582318973321ded4f59059aed2230d51212d780eb56174e796a2e15655a51e1d655f0003b809ca6beb1b5ca; msToken=_z0IcVwSTp3tAznsgpP3pOd1gbvkj-hwuwQ66E_bkI3StjmVjcm1S_LVAEZC_FeIAVgw6ptaov-6-IhVVqMuu_Pd778WplvLDUh5fjgzYMMX4yNK6rx3iQ==',
      'sec-ch-ua': '"Not_A Brand";v="8", "Chromium";v="120", "Google Chrome";v="120"',
      'accept': 'application/json, text/plain, */*',
      'x-secsdk-csrf-token': '000100000001659f236613984139ebcfbd538a9b9eb67315152b7bd57dd6a644166a279dab2e17ab0611f11eeca8',
      'sec-ch-ua-mobile': '?0',
      'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
      'sec-ch-ua-platform': '"macOS"',
      'sec-fetch-site': 'same-origin',
      'sec-fetch-mode': 'cors',
      'sec-fetch-dest': 'empty',
      'referer': 'https://creator.douyin.com/creator-micro/content/publish?enter_from=publish_page',
      'accept-language': 'zh-CN,zh;q=0.9',
    };
    return defer(() =>
      axios.get(uri, { params, headers }),
    ).pipe(
      map(res => {
        // {
        //   "ak": "AKLTYjdjYTUwZWQwZDU0NDRmMmEwNWU5NmE1MTdiYzUyZTg",
        //   "auth": "{\"AccessKeyID\":\"AKTPZTU5YzZjNDUwMGYyNDcwMzkzYTI4ZWNmMGY3OTU5OTM\",\"SecretAccessKey\":\"fBTCJScp1TsFInu6e1veijHbwWZvgnyx2TXVreBJ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b25cIjpbXCJQU01cIl0sXCJSZXNvdXJjZVwiOltcImRvdXlpbi5jcmVhdG9yLmNvbnRlbnRcIl19XX0iLCJTaWduYXR1cmUiOiIwNWE1YzI1NmZlMDA4YjVkNjkyOThlOWMxZjkwMTRlZjE2YWU3YmI3OTAzMjdmZjllZTg5ZjNlZWI5NGZhMTdlIn0=\",\"ExpiredTime\":\"2024-01-19T17:13:43+08:00\",\"CurrentTime\":\"2024-01-17T17:13:43+08:00\"}",
        //   "extra": {
        //   "logid": "2024011717134329C33002D16B5D01F1C7",
        //     "now": 1705482823000
        // },
        //   "status_code": 0
        // }
        if (res.data?.status_code !== 0) {
          throw new HttpException(`Get upload auth failed.`, HttpStatus.BAD_REQUEST);
        }
        task.res_requestAuth = res.data;
        return task;
      }),
    );
  }

  uploadVideo_applyUploadInner(task: DyUploadTask) {
    const uri: string = 'https://vod.bytedanceapi.com/';
    const uploadAuth = this.getTaskUploadAuth(task);
    const params = {
      'Action': 'ApplyUploadInner',
      'Version': '2020-11-19',
      'SpaceName': 'aweme',
      'FileType': 'video',
      'IsInner': '1',
      'FileSize': task.videoFile.size,
      'app_id': '2906',
      'user_id': '572219949591661',
      's': Math.random().toString(36).substring(2),
    };
    const request: DyHelperRequest = {
      headers: {},
      params,
      body: undefined,
      pathname: DyHelper.getPathByURL(uri),
      region: 'cn-north-1',
      timeout: 3000,
      url: uri,
      method: 'GET',
    };
    const dyHelper = new DyHelper(request, 'vod');
    const authHeaders = dyHelper.addAuthorization({
      accessKeyId: uploadAuth.AccessKeyID,
      secretAccessKey: uploadAuth.SecretAccessKey,
      sessionToken: uploadAuth.SessionToken,
    }, new Date());

    const headers = {
      'Host': 'vod.bytedanceapi.com',
      'sec-ch-ua': '"Not_A Brand";v="8", "Chromium";v="120", "Google Chrome";v="120"',
      'x-amz-security-token': 'STS2eyJMVEFjY2Vzc0tleUlEIjoiQUtMVFlqZGpZVFV3WldRd1pEVTBORFJtTW1Fd05XVTVObUUxTVRkaVl6VXlaVG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jg4MDYxZDY5NzUwN2E0OTgyOTFhNDEyZGUyYTVmMmZhNjMzMWM1NDk5NzczYThlOTQ5ZmU4In0=',
      'x-amz-date': '20240117T035550Z',
      'sec-ch-ua-mobile': '?0',
      'authorization': 'AWS4-HMAC-SHA256 Credential=AKTPMzAyMjc2YzU3NTE0NDhjOTgxZWU0N2U3MGU0Y2U3NjU/20240117/cn-north-1/vod/aws4_request, SignedHeaders=x-amz-date;x-amz-security-token, Signature=da26c56dfc31fab79db5ba8ec37936a3dd13a22cfd7dc3e6990186edcb305c10',
      'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
      'sec-ch-ua-platform': '"macOS"',
      'accept': '*/*',
      'origin': 'https://creator.douyin.com',
      'sec-fetch-site': 'cross-site',
      'sec-fetch-mode': 'cors',
      'sec-fetch-dest': 'empty',
      'referer': 'https://creator.douyin.com/',
      'accept-language': 'zh-CN,zh;q=0.9',
      ...authHeaders,
    };
    return defer(() =>
      axios.get(uri, { params, headers }),
    ).pipe(
      map(res => {
        if (!Array.isArray(res.data?.Result?.InnerUploadAddress?.UploadNodes) || res.data?.Result?.InnerUploadAddress?.UploadNodes.length <= 0) {
          throw new HttpException(`ApplyUploadInner request failed.`, HttpStatus.BAD_REQUEST);
        }
        if (!task.res_uploadVideo) {
          task.res_uploadVideo = {};
        }
        task.res_uploadVideo.res_uploadCover_applyUploadInner = res.data;
        return task;
      }),
    );
  }

  getUploadId(): string {
    return crypto.randomUUID();
  }

  uploadVideo_uploadFullVideo(task: DyUploadTask) {
    const prePartLength = 3145728;
    const buffer = task.videoFile.buffer;
    const totalPart = Math.ceil(buffer.length / prePartLength);
    const uploadId = this.getUploadId();
    const uploadNode = this.parseUploadNode(task.res_uploadVideo.res_uploadCover_applyUploadInner);
    const partList: DyUploadPart[] = IHelper.getArray(totalPart).map(idx => {
      const partBuffer = buffer.subarray(idx * prePartLength, (idx + 1) * prePartLength);
      return {
        buffer: partBuffer,
        crc32: DyHelper.getBufferHash(partBuffer),
        uploadId,
        offset: (idx * prePartLength).toString(),
        idx: (idx + 1).toString(),
        node: uploadNode,
      };
    });
    return forkJoin(
      [...partList.map(part => this.uploadVideo_uploadPrePart(part))],
    ).pipe(
      map(d => {
        task.res_uploadVideo.res_uploadCover_uploadFullVideo = d;
      }),
      concatMap(() => this.uploadVideo_mergeVideo(partList)),
      map(d => {
        task.res_uploadVideo.res_uploadCover_mergeVideo = d;
        return task;
      }),
    );
  }

  uploadVideo_uploadPrePart(part: DyUploadPart) {
    const params = {
      'uploadid': part.uploadId,
      'part_number': part.idx,
      'phase': 'transfer',
      'part_offset': part.offset,
    };
    const headers: RawAxiosRequestHeaders = {
      'Host': part.node.UploadHost,
      'Pragma': 'no-cache',
      'Cache-Control': 'no-cache',
      'sec-ch-ua': '"Not_A Brand";v="8", "Chromium";v="120", "Google Chrome";v="120"',
      'X-Storage-U': '572219949591661',
      'Content-CRC32': part.crc32,
      'sec-ch-ua-mobile': '?0',
      'Authorization': part.node.Auth,
      'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
      'Content-Type': 'application/octet-stream',
      'Content-Disposition': 'attachment; filename="undefined"',
      'sec-ch-ua-platform': '"macOS"',
      'Accept': '*/*',
      'Origin': 'https://creator.douyin.com',
      'Sec-Fetch-Site': 'same-site',
      'Sec-Fetch-Mode': 'cors',
      'Sec-Fetch-Dest': 'empty',
      'Referer': 'https://creator.douyin.com/',
      'Accept-Language': 'zh-CN,zh;q=0.9',
    };
    return defer(() =>
      axios.post(part.node.UploadUri, part.buffer, { params, headers }),
    ).pipe(
      map(res => {
        if (res.data?.code !== 2000) {
          throw new HttpException(`UploadVideo_uploadPrePart res code not 2000.`, HttpStatus.BAD_REQUEST);
        }
        if (res.data?.data?.crc32 !== part.crc32) {
          throw new HttpException(`UploadVideo_uploadPrePart res crc32 not match.`, HttpStatus.BAD_REQUEST);
        }
        return res.data;
      }),
    );
  }

  uploadVideo_mergeVideo(partList: DyUploadPart[]) {
    const uri: string = partList[0].node.UploadUri;
    const data: string = partList.map(part => `${part.idx}:${part.crc32}`).join(',');
    const params = {
      'uploadmode': 'part',
      'phase': 'finish',
      'uploadid': partList[0].uploadId,
    };
    const headers: RawAxiosRequestHeaders = {
      'Host': partList[0].node.UploadHost,
      'Pragma': 'no-cache',
      'Cache-Control': 'no-cache',
      'sec-ch-ua': '"Not_A Brand";v="8", "Chromium";v="120", "Google Chrome";v="120"',
      'Content-Type': 'text/plain;charset=UTF-8',
      'X-Storage-U': '572219949591661',
      'sec-ch-ua-mobile': '?0',
      'Authorization': partList[0].node.Auth,
      'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
      'sec-ch-ua-platform': '"macOS"',
      'Accept': '*/*',
      'Origin': 'https://creator.douyin.com',
      'Sec-Fetch-Site': 'cross-site',
      'Sec-Fetch-Mode': 'cors',
      'Sec-Fetch-Dest': 'empty',
      'Referer': 'https://creator.douyin.com/',
      'Accept-Language': 'zh-CN,zh;q=0.9',
    };
    return defer(() =>
      axios.post(uri, data, { params, headers }),
    ).pipe(
      map(res => res.data),
    );
  }

  uploadVideo_commitUploadInner(task: DyUploadTask) {
    const uri: string = `https://vod.bytedanceapi.com/`;
    const uploadAuth = this.getTaskUploadAuth(task);
    let uploadNode = this.parseUploadNode(task.res_uploadVideo.res_uploadCover_applyUploadInner);
    const data = {
      'SessionKey': uploadNode.SessionKey,
      'Functions': [{ 'name': 'GetMeta' }, { 'name': 'Snapshot', 'input': { 'SnapshotTime': 0 } }],
    };
    const params = {
      'Action': 'CommitUploadInner',
      'Version': '2020-11-19',
      'SpaceName': 'aweme',
      'app_id': '2906',
      'user_id': '572219949591661',
    };
    const request: DyHelperRequest = {
      headers: {},
      params,
      body: { ...data },
      pathname: DyHelper.getPathByURL(uri),
      region: 'cn-north-1',
      timeout: 3000,
      url: uri,
      method: 'POST',
    };
    const dyHelper = new DyHelper(request, 'vod');
    const authHeaders = dyHelper.addAuthorization({
      accessKeyId: uploadAuth.AccessKeyID,
      secretAccessKey: uploadAuth.SecretAccessKey,
      sessionToken: uploadAuth.SessionToken,
    }, new Date());
    const headers: RawAxiosRequestHeaders = {
      'Host': 'vod.bytedanceapi.com',
      'pragma': 'no-cache',
      'cache-control': 'no-cache',
      'sec-ch-ua': '"Not_A Brand";v="8", "Chromium";v="120", "Google Chrome";v="120"',
      'sec-ch-ua-mobile': '?0',
      'authorization': 'AWS4-HMAC-SHA256 Credential=AKTPOTQ3NWE5MzgxMDFmNGM1ZmFjNGZlNDk5MTZhMzc1MTM/20240118/cn-north-1/vod/aws4_request, SignedHeaders=x-amz-content-sha256;x-amz-date;x-amz-security-token, Signature=86b40ce6add68a456a5af11e396111eea16a1cb277025eacc27f86f6e9cd8436',
      'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
      'content-type': 'text/plain;charset=UTF-8',
      'x-amz-content-sha256': 'e2899101736914fcbd5c1db446fb1bc6e2fb0f8650d115efc304282fd799478c',
      'x-amz-security-token': 'STS2eyJMVEFjY2Vzc0tleUlEIjoiQUtMVFlqZGpZVFV3WldRd1pEVTBORFJtTW1Fd05XVTVObUUxTVRkaVl6VXlaVGciLCJBY2Nlc3NLZXlJRCI6IkFLVFBPVFEzTldFNU16Z3hNREZtTkdNMVptRmpOR1psTkRrNU1UWmhNemMxTVRNIiwiU2lnbmVkU2VjcmV0QWNjZXNzS2V5IjoiVURMVzRCeWlCb2hGL1I5NWhwMkpHeWF1cFREM1NFNk9EbkJ3cEZZMytRR082VmoveDFnQlk2dGFHcEFwZm9QRno0N241amFXUCtWd0hWOW1jRDZCaFplNVBBSStEQlVZZ2F4NXZPTVZyUms9IiwiRXhwaXJlZFRpbWUiOjE3MDU3MTcwODMsIlBvbGljeVN0cmluZyI6IntcIlN0YXRlbWVudFwiOlt7XCJFZmZlY3RcIjpcIkFsbG93XCIsXCJBY3Rpb25cIjpbXCJ2b2Q6KlwiLFwiSW1hZ2VYOipcIl0sXCJSZXNvdXJjZVwiOltcIipcIl19LHtcIkVmZmVjdFwiOlwiQWxsb3dcIixcIkFjdGlvblwiOltcIlVzZXJJZFwiXSxcIlJlc291cmNlXCI6W1wiNTcyMjE5OTQ5NTkxNjYxXCJdfSx7XCJFZmZlY3RcIjpcIkFsbG93XCIsXCJBY3Rpb25cIjpbXCJBcHBJZFwiXSxcIlJlc291cmNlXCI6W1wiMTEyOFwiXX0se1wiRWZmZWN0XCI6XCJBbGxvd1wiLFwiQWN0aW9uXCI6W1wiVXNlclJlZmVyZW5jZVwiXSxcIlJlc291cmNlXCI6W1wie1xcXCJwc21cXFwiOlxcXCJkb3V5aW4uY3JlYXRvci5jb250ZW50XFxcIn1cIl19LHtcIkVmZmVjdFwiOlwiQWxsb3dcIixcIkFjdGlvblwiOltcIlNlc3Npb25DaGVja1wiXSxcIlJlc291cmNlXCI6W1wiVWlkXCJdfSx7XCJFZmZlY3RcIjpcIkFsbG93XCIsXCJBY3Rpb25cIjpbXCJQU01cIl0sXCJSZXNvdXJjZVwiOltcImRvdXlpbi5jcmVhdG9yLmNvbnRlbnRcIl19XX0iLCJTaWduYXR1cmUiOiJlN2VjZjY0ZWQ1MmMwYTdjOGY3OTI0OGE0ZjYwNWZmNmIyNTRiNGYxZGM1NjY2NWRmNWY3ZTg0ZDEyZjg4OTkwIn0=',
      'x-amz-date': '20240118T021806Z',
      'sec-ch-ua-platform': '"macOS"',
      'accept': '*/*',
      'origin': 'https://creator.douyin.com',
      'sec-fetch-site': 'cross-site',
      'sec-fetch-mode': 'cors',
      'sec-fetch-dest': 'empty',
      'referer': 'https://creator.douyin.com/',
      'accept-language': 'zh-CN,zh;q=0.9',
      ...authHeaders,
    };
    return defer(() =>
      axios.post(uri, JSON.stringify(data), { params, headers }),
    ).pipe(
      map(res => {
        task.res_uploadVideo.res_uploadCover_commitUploadInner = res.data;
        return task;
      }),
    );
  }

  uploadCover(task: DyUploadTask) {
    return this.uploadCover_applyImageUpload(task).pipe(
      concatMap(() => this.uploadCover_upload(task)),
      concatMap(() => this.uploadCover_commitImageUpload(task)),
      retry(10),
    );
  }

  uploadCover_applyImageUpload(task: DyUploadTask): Observable<DyUploadTask> {
    const uri: string = `https://imagex.bytedanceapi.com/`;
    const uploadAuth = this.getTaskUploadAuth(task);
    const params = {
      'Action': 'ApplyImageUpload',
      'Version': '2018-08-01',
      'ServiceId': 'jm8ajry58r',
      'app_id': '2906',
      'user_id': '572219949591661',
      's': Math.random().toString(36).substring(2),
    };
    const request: DyHelperRequest = {
      headers: {},
      params,
      body: undefined,
      pathname: DyHelper.getPathByURL(uri),
      region: 'cn-north-1',
      timeout: 3000,
      url: uri,
      method: 'GET',
    };
    const dyHelper = new DyHelper(request, 'imagex');
    const authHeaders = dyHelper.addAuthorization({
      accessKeyId: uploadAuth.AccessKeyID,
      secretAccessKey: uploadAuth.SecretAccessKey,
      sessionToken: uploadAuth.SessionToken,
    }, new Date());
    const headers = {
      'Host': 'imagex.bytedanceapi.com',
      'pragma': 'no-cache',
      'cache-control': 'no-cache',
      'sec-ch-ua': '"Not_A Brand";v="8", "Chromium";v="120", "Google Chrome";v="120"',
      'x-amz-security-token': 'STS2eyJMVEFjY2Vzc0tleUlEIjoiQUtMVFlqZGpZVFV3WldRd1pEVTBORFJtTW1Fd05XVTVObUUxTVRkaVl6VXlaVGciLCJBY2Nlc3NLZXlJRCI6IkFLVFBORGs0T1dVM05EVXhPRFV3TkdWbFptRmxPR0pqWmpZeE1tSTBaVEF5WTJNIiwiU2lnbmVkU2VjcmV0QWNjZXNzS2V5IjoidXEwakdyMGFSREh5Rk5YSHFweDRLcFBFT3ZxemwxRFNZa1FPMUZCTWFIM1FJ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TAyY2M/20240118/cn-north-1/imagex/aws4_request, SignedHeaders=x-amz-date;x-amz-security-token, Signature=b0c5379a0f3a7f33c700e35939458b7488d0e8fe6e91d60eb4f9273663af2793',
      'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
      'sec-ch-ua-platform': '"macOS"',
      'accept': '*/*',
      'origin': 'https://creator.douyin.com',
      'sec-fetch-site': 'cross-site',
      'sec-fetch-mode': 'cors',
      'sec-fetch-dest': 'empty',
      'referer': 'https://creator.douyin.com/',
      'accept-language': 'zh-CN,zh;q=0.9',
      ...authHeaders,
    };
    return defer(() =>
      axios.get('https://imagex.bytedanceapi.com/', { params, headers }),
    ).pipe(
      map(res => {
        if (!Array.isArray(res.data?.Result?.InnerUploadAddress?.UploadNodes) || res.data?.Result?.InnerUploadAddress?.UploadNodes.length <= 0) {
          throw new HttpException(`UploadCover_applyImageUpload failed.`, HttpStatus.BAD_REQUEST);
        }
        if (!task.res_uploadCover) {
          // @ts-ignore
          task.res_uploadCover = {};
        }
        task.res_uploadCover.res_uploadCover_applyImageUpload = res.data;
        console.log('res.data', res.data);
        return task;
      }),
    );
  }

  uploadCover_upload(task: DyUploadTask) {
    const uploadNode = this.parseUploadNode(task.res_uploadCover.res_uploadCover_applyImageUpload);
    const crc32: string = DyHelper.getBufferHash(task.coverFile.buffer);
    const headers: RawAxiosRequestHeaders = {
      'Host': 'tos-d-ct-lf.snssdk.com',
      'Pragma': 'no-cache',
      'Cache-Control': 'no-cache',
      'sec-ch-ua': '"Not_A Brand";v="8", "Chromium";v="120", "Google Chrome";v="120"',
      'X-Storage-U': '572219949591661',
      'Content-CRC32': crc32,
      'sec-ch-ua-mobile': '?0',
      'Authorization': uploadNode.Auth,
      'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
      'Content-Type': 'application/octet-stream',
      'Content-Disposition': 'attachment; filename="undefined"',
      'sec-ch-ua-platform': '"macOS"',
      'Accept': '*/*',
      'Origin': 'https://creator.douyin.com',
      'Sec-Fetch-Site': 'cross-site',
      'Sec-Fetch-Mode': 'cors',
      'Sec-Fetch-Dest': 'empty',
      'Referer': 'https://creator.douyin.com/',
      'Accept-Language': 'zh-CN,zh;q=0.9',
    };
    const buffer = new Uint8Array(task.coverFile.buffer).buffer;
    return defer(() =>
      axios.post(uploadNode.UploadUri, buffer, { headers }),
    ).pipe(
      map(res => {
        if (res.data?.data?.crc32 !== crc32) {
          throw new HttpException(`UploadCover_upload failed.`, HttpStatus.BAD_REQUEST);
        }
        task.res_uploadCover.res_uploadCover_upload = res.data;
        return task;
      }),
    );
  }

  uploadCover_commitImageUpload(task: DyUploadTask) {
    const uri: string = 'https://imagex.bytedanceapi.com/';
    const uploadNode = this.parseUploadNode(task.res_uploadCover.res_uploadCover_applyImageUpload);
    const uploadAuth = this.getTaskUploadAuth(task);
    const data: any = {
      'SessionKey': uploadNode.SessionKey,
    };
    const params = {
      'Action': 'CommitImageUpload',
      'Version': '2018-08-01',
      'ServiceId': 'jm8ajry58r',
      'app_id': '2906',
      'user_id': '572219949591661',
    };
    const request: DyHelperRequest = {
      headers: {},
      params,
      body: { ...data },
      pathname: DyHelper.getPathByURL(uri),
      region: 'cn-north-1',
      timeout: 3000,
      url: uri,
      method: 'POST',
    };
    const dyHelper: DyHelper = new DyHelper(request, 'imagex');
    const authHeaders: RawAxiosRequestHeaders = dyHelper.addAuthorization(
      {
        accessKeyId: uploadAuth.AccessKeyID,
        secretAccessKey: uploadAuth.SecretAccessKey,
        sessionToken: uploadAuth.SessionToken,
      },
      new Date(),
    );
    const headers = {
      'Host': 'imagex.bytedanceapi.com',
      'pragma': 'no-cache',
      'cache-control': 'no-cache',
      'sec-ch-ua': '"Not_A Brand";v="8", "Chromium";v="120", "Google Chrome";v="120"',
      'sec-ch-ua-mobile': '?0',
      'authorization': 'AWS4-HMAC-SHA256 Credential=AKTPNDk4OWU3NDUxODUwNGVlZmFlOGJjZjYxMmI0ZTAyY2M/20240118/cn-north-1/imagex/aws4_request, SignedHeaders=x-amz-content-sha256;x-amz-date;x-amz-security-token, Signature=25ee481254bd4ca6d91dc07b93988e20059bd8992b147f392422a78d00e6802f',
      'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
      'content-type': 'application/json',
      'x-amz-content-sha256': 'ac70aee180d912f5cee047150b1725aad3c2b623fceda800a721adcbaf93f2e8',
      'x-amz-security-token': 'STS2eyJMVEFjY2Vzc0tleUlEIjoiQUtMVFlqZGpZVFV3WldRd1pEVTBORFJtTW1Fd05XVTVObUUxTVRkaVl6VXlaVGciLCJBY2Nlc3NLZXlJRCI6IkFLVFBORGs0T1dVM05EVXhPRFV3TkdWbFptRmxPR0pqWmpZeE1tSTBaVEF5WTJNIiwiU2lnbmVkU2VjcmV0QWNjZXNzS2V5IjoidXEwakdyMGFSREh5Rk5YSHFweDRLcFBFT3ZxemwxRFNZa1FPMUZCTWFIM1FJMVZadVI1NW9VeDgrL0EyeFordmdqZkgzbXRIWFlnWFh0RUloMjVhR3FtOG10UEo4WkJPVW5nYVdpclVEblU9IiwiRXhwaXJlZFRpbWUiOjE3MDU3NDMwOTgsIlBvbGljeVN0cmluZyI6IntcIlN0YXRlbWVudFwiOlt7XCJFZmZlY3RcIjpcIkFsbG93XCIsXCJBY3Rpb25cIjpbXCJ2b2Q6KlwiLFwiSW1hZ2VYOipcIl0sXCJSZXNvdXJjZVwiOltcIipcIl19LHtcIkVmZmVjdFwiOlwiQWxsb3dcIixcIkFjdGlvblwiOltcIlVzZXJJZFwiXSxcIlJlc291cmNlXCI6W1wiNTcyMjE5OTQ5NTkxNjYxXCJdfSx7XCJFZmZlY3RcIjpcIkFsbG93XCIsXCJBY3Rpb25cIjpbXCJBcHBJZFwiXSxcIlJlc291cmNlXCI6W1wiMTEyOFwiXX0se1wiRWZmZWN0XCI6XCJBbGxvd1wiLFwiQWN0aW9uXCI6W1wiVXNlclJlZmVyZW5jZVwiXSxcIlJlc291cmNlXCI6W1wie1xcXCJwc21cXFwiOlxcXCJkb3V5aW4uY3JlYXRvci5jb250ZW50XFxcIn1cIl19LHtcIkVmZmVjdFwiOlwiQWxsb3dcIixcIkFjdGlvblwiOltcIlNlc3Npb25DaGVja1wiXSxcIlJlc291cmNlXCI6W1wiVWlkXCJdfSx7XCJFZmZlY3RcIjpcIkFsbG93XCIsXCJBY3Rpb25cIjpbXCJQU01cIl0sXCJSZXNvdXJjZVwiOltcImRvdXlpbi5jcmVhdG9yLmNvbnRlbnRcIl19XX0iLCJTaWduYXR1cmUiOiI3ZDdlODI4ZTUzYWI4YzEzNTcxNTdkODAyNDNhOTFlZmNkMjZiODI0ODIxM2NlZmY1YmRhZTgwNTQ4ZTJkZTBkIn0=',
      'x-amz-date': '20240118T093139Z',
      'sec-ch-ua-platform': '"macOS"',
      'accept': '*/*',
      'origin': 'https://creator.douyin.com',
      'sec-fetch-site': 'cross-site',
      'sec-fetch-mode': 'cors',
      'sec-fetch-dest': 'empty',
      'referer': 'https://creator.douyin.com/',
      'accept-language': 'zh-CN,zh;q=0.9',
      ...authHeaders,
    };
    return defer(() =>
      axios.post(uri, data, { params, headers }),
    ).pipe(
      map(res => {
        console.log('res', res.data);
        if (!Array.isArray(res.data?.Result?.Results) || res.data?.Result?.Results.length <= 0) {
          throw new HttpException(`UploadCover_commitImageUpload failed.`, HttpStatus.BAD_REQUEST);
        }
        task.res_uploadCover.res_uploadCover_commitImageUpload = res.data;
        return task;
      }),
    );
  }

  buildPubTitleConfig(task: DyUploadTask) {
    const title: string = task.config.title;
    const tagList: string[] = task.config.tag.split(',');
    const tagStr: string = tagList.map(e => `#${e}`).join(' ');
    const text_extra = tagList.map(e => `#${e}`).map((tag, idx) => {
      let beforeLength = tagList.slice(0, idx).map(e => `#${e}`).join(" ").length + (idx > 0 ? 1 : 0)
      return {
        caption_end: beforeLength + tag.length,
        caption_start: beforeLength,
        end: beforeLength + tag.length + (title.length + 1),
        hashtag_id: 0,
        hashtag_name: tag,
        start: beforeLength + (title.length + 1),
        type: 1,
        user_id: '',
      };
    });
    return {
      item_title: title,
      caption: tagStr,
      text: `${title} ${tagStr}`,
      text_extra: JSON.stringify(text_extra),
    };
  }

  publishTask(task: DyUploadTask) {
    const uri: string = 'https://creator.douyin.com/web/api/media/aweme/create/';

    const params = {
      // "cookie_enabled": "true",
      // "screen_width": "1920",
      // "screen_height": "1080",
      // "browser_language": "zh-CN",
      // "browser_platform": "MacIntel",
      // "browser_name": "Mozilla",
      // "browser_version": "5.0+(Macintosh;+Intel+Mac+OS+X+10_15_7)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/120.0.0.0+Safari/537.36",
      // "browser_online": "true",
      // "timezone_name": "Asia/Shanghai",
      // "aid": "1128",
      // "msToken": "Bpbffw37-Ion74pJDRpXb8VDpU1uJQZ53kv6UHhMoqK3ppu4x0usdcQPyR1fNVvjaVGev8tCJQFTafhO9AZN9fE1FpukGYAgT4QiDCf0GI_NEfy0hH7aoA",
      // "a_bogus": "DJld6c2pMsm1ZjlBxXkz9aDMXlb0YW4qgZENy-pPhtqy",
      // "X-Bogus": "DFSzsdVLwrsTcAP7tijy/5RXoR0u",
      // "_signature": "_02B4Z6wo00001pQRFbgAAIDDejTRRzZcuE6UFREAAMC4kAG0IX-vJgtFbWuhSfCVZb5fyAe1mcRtKh8aCGDWynjIc0Ex7-Ww80.cwryRQcDZ5MQzi6T3tauEQtnhBsVYV6jXomt3GJAiz2Dabc"
    };
    const data = new URLSearchParams({
      'video_id': task.res_uploadVideo.res_uploadCover_commitUploadInner.Result.Results[0].Vid,
      'ifLongTitle': 'true',
      'text': '你哈你好 21312313#23213 #awdwd',
      'caption': task.config.tag.split(',').map(t => `#${t}`).join(' '),
      'item_title': task.config.title,
      'record': 'null',
      'source_info': '{}',
      'activity': '[]',
      'text_extra': '[{"start":13,"end":19,"type":1,"hashtag_name":"23213","hashtag_id":0,"user_id":"","caption_start":8,"caption_end":14},{"start":20,"end":26,"type":1,"hashtag_name":"awdwd","hashtag_id":0,"user_id":"","caption_start":15,"caption_end":21}]',
      'challenges': '[]',
      'mentions': '[]',
      'hashtag_source': '"search/search"',
      'visibility_type': '0',
      'upload_source': '1',
      'is_preview': '0',
      'is_post_assistant': '1',
      'user_declare_info': '{}',
      'hot_sentence': '',
      'knowl_id': '',
      'knowl_order': '0',
      'title_permission': '1',
      'creation_id': IHelper.hash(21) || '7r18qoge1705569261603',
      'poster': task.res_uploadCover.res_uploadCover_commitImageUpload.Result.Results[0].Uri,
      'poster_delay': '0',
      'timing': '0',
      'music_source': '0',
      'music_id': '',
      'download': '1',
      'poster_param': '{}',
      // 'custom_cover_image_height': '504',
      // 'custom_cover_image_width': '672',
      // 'cover_tools_info': '{"cover_width":672,"cover_height":504,"cover_type":"upload","video_cover_source":"upload","is_text_template":0,"is_text":0,"text_num":0,"is_cover_template":0,"tab_name":"","sticker_tab_name":"","filter_tab_name":"","text_content":"","text_template_content":"","is_use_sticker":0,"is_use_filter":0,"text_template_id":"","sticker_id":"","filter_id":[],"recommend_timestamp":"{23600,47200,0}"}',
      'chapter': '{"chapter_details":[],"chapter_type":1}',
      ...this.buildPubTitleConfig(task),
    });
    const headers: RawAxiosRequestHeaders = {
      'Host': 'creator.douyin.com',
      'Cookie': 'bd_ticket_guard_client_web_domain=2; passport_csrf_token=8ac577ac5cad0f1a486aaad9e00cb304; passport_csrf_token_default=8ac577ac5cad0f1a486aaad9e00cb304; volume_info=%7B%22isUserMute%22%3Afalse%2C%22isMute%22%3Atrue%2C%22volume%22%3A0.6%7D; strategyABtestKey=%221705463377.324%22; FORCE_LOGIN=%7B%22videoConsumedRemainSeconds%22%3A180%2C%22isForcePopClose%22%3A1%7D; _tea_utm_cache_2906=undefined; s_v_web_id=lrh8v340_Iufk7QSy_PJYo_4gxu_AfOa_cmHysRjcmWmL; pwa2=%220%7C0%7C1%7C0%22; passport_assist_user=CkDljygontbPJ87N3y9FkFKscatGwjQQgs04KqiBZW3LqVs4tJ00j5WCW4ysoht6fiZl8M1pI7GenqL49FkrR6r4GkoKPPE4ePu6muJXDD1HJyHNHM_T7dq2kxpAFL5wiOVx9-vPD14wZH2UzXwb3aGBBeph_AqB_sQvDgYWNY4mDhCP8cYNGImv1lQgASIBAzYfpV4%3D; n_mh=CVCcgMkWFJlJavMf5K1rAr0kZbZmZbXiNogVcvAYS14; sso_uid_tt=d9899fd058f37229c87972a34759ed1f; sso_uid_tt_ss=d9899fd058f37229c87972a34759ed1f; toutiao_sso_user=9aa743193ce0358c5e33412736b210e0; toutiao_sso_user_ss=9aa743193ce0358c5e33412736b210e0; sid_ucp_sso_v1=1.0.0-KDI5ZmFmMTJiZmUyY2EzYzlkMGNlZDcwNzY1NmU1OGUxNzRiYTgyZGEKHwjt2NC25Y2CARCEnp2tBhjaFiAMMJHalY8GOAZA9AcaAmxxIiA5YWE3NDMxOTNjZTAzNThjNWUzMzQxMjczNmIyMTBlMA; ssid_ucp_sso_v1=1.0.0-KDI5ZmFmMTJiZmUyY2EzYzlkMGNlZDcwNzY1NmU1OGUxNzRiYTgyZGEKHwjt2NC25Y2CARCEnp2tBhjaFiAMMJHalY8GOAZA9AcaAmxxIiA5YWE3NDMxOTNjZTAzNThjNWUzMzQxMjczNmIyMTBlMA; passport_auth_status=55a0f2bab99008a835be7481fa43d207%2C; passport_auth_status_ss=55a0f2bab99008a835be7481fa43d207%2C; uid_tt=15ac3dcdb321c6dcafd58d4f27cfaaf5; uid_tt_ss=15ac3dcdb321c6dcafd58d4f27cfaaf5; sid_tt=380ada5aa45d24dd94617759cca38f45; sessionid=380ada5aa45d24dd94617759cca38f45; sessionid_ss=380ada5aa45d24dd94617759cca38f45; csrf_session_id=80aae493eb9e20f3d60070094d4f6ace; oc_login_type=LOGIN_PERSON; _bd_ticket_crypt_doamin=2; _bd_ticket_crypt_cookie=1ba2128c644dcc42f2439e82d22a5794; __security_server_data_status=1; sid_guard=380ada5aa45d24dd94617759cca38f45%7C1705463559%7C5183999%7CSun%2C+17-Mar-2024+03%3A52%3A38+GMT; sid_ucp_v1=1.0.0-KDhjMDY0YjY4YThkODVkYWY3YjgzM2IxMGZhYTA1N2RhYjllNzNkZmEKGwjt2NC25Y2CARCHnp2tBhjaFiAMOAZA9AdIBBoCbGYiIDM4MGFkYTVhYTQ1ZDI0ZGQ5NDYxNzc1OWNjYTM4ZjQ1; ssid_ucp_v1=1.0.0-KDhjMDY0YjY4YThkODVkYWY3YjgzM2IxMGZhYTA1N2RhYjllNzNkZmEKGwjt2NC25Y2CARCHnp2tBhjaFiAMOAZA9AdIBBoCbGYiIDM4MGFkYTVhYTQ1ZDI0ZGQ5NDYxNzc1OWNjYTM4ZjQ1; publish_badge_show_info=%220%2C0%2C0%2C1705465764029%22; stream_recommend_feed_params=%22%7B%5C%22cookie_enabled%5C%22%3Atrue%2C%5C%22screen_width%5C%22%3A1920%2C%5C%22screen_height%5C%22%3A1080%2C%5C%22browser_online%5C%22%3Atrue%2C%5C%22cpu_core_num%5C%22%3A12%2C%5C%22device_memory%5C%22%3A8%2C%5C%22downlink%5C%22%3A10%2C%5C%22effective_type%5C%22%3A%5C%224g%5C%22%2C%5C%22round_trip_time%5C%22%3A0%7D%22; LOGIN_STATUS=1; FOLLOW_LIVE_POINT_INFO=%22MS4wLjABAAAAnXGfCZQX80xazjPRiz9R1fZnXb5tcRFn1Jp3Orx90Oc%2F1705507200000%2F0%2F1705465764414%2F0%22; home_can_add_dy_2_desktop=%221%22; IsDouyinActive=false; stream_player_status_params=%22%7B%5C%22is_auto_play%5C%22%3A0%2C%5C%22is_full_screen%5C%22%3A0%2C%5C%22is_full_webscreen%5C%22%3A0%2C%5C%22is_mute%5C%22%3A1%2C%5C%22is_speed%5C%22%3A1%2C%5C%22is_visible%5C%22%3A0%7D%22; passport_fe_beating_status=true; ttwid=1%7Co95Gjgo8evGWkYs0q1d0-pZsGAh_1ET-tzwv5V7NhoE%7C1705569251%7C6b13d9d5fccea1e472ae2b57d8b9f6b7ae13268d62efd9297b8c35dbaf101cbd; bd_ticket_guard_client_data=eyJiZC10aWNrZXQtZ3VhcmQtdmVyc2lvbiI6MiwiYmQtdGlja2V0LWd1YXJkLWl0ZXJhdGlvbi12ZXJzaW9uIjoxLCJiZC10aWNrZXQtZ3VhcmQtcmVlLXB1YmxpYy1rZXkiOiJCRlpNMTBtQk03REoyaGtIOG1DQjhYNXdtMkZKSEthRXpBclI1TGpseCtyRXVvZTliL3pBcTdrRFRmMHhDbUIxaVZCK1lmSytiVFp0MXlQNDgxNWZ6dXM9IiwiYmQtdGlja2V0LWd1YXJkLXdlYi12ZXJzaW9uIjoxfQ%3D%3D; tt_scid=OX7P4Jh.hhS3yaMfIp2UTVlboO85memWrs640nzuBvEG2BhNIo-4Dj5fnIgIudmc429f; msToken=Bpbffw37-Ion74pJDRpXb8VDpU1uJQZ53kv6UHhMoqK3ppu4x0usdcQPyR1fNVvjaVGev8tCJQFTafhO9AZN9fE1FpukGYAgT4QiDCf0GI_NEfy0hH7aoA==; msToken=2ySk_Q0ESa-BgVmpslpLm4roSQ6tsaxHnDVm6v6KmjDNhGaRA9QWbw3cUo3ZeyNTMCsMBW3ta6eZIFKWPhMPK48l4PginUsljYE_28Uxt6cPpsCrdqouwg==; odin_tt=184eec188d690f9d1d76e8187ecc36785c484570d3fcc03a11bc926948fcf68a991d63c9b9c3c9278468aa0e3b915263',
      'pragma': 'no-cache',
      'cache-control': 'no-cache',
      'bd-ticket-guard-version': '2',
      'sec-ch-ua': '"Not_A Brand";v="8", "Chromium";v="120", "Google Chrome";v="120"',
      'bd-ticket-guard-iteration-version': '1',
      'bd-ticket-guard-ree-public-key': 'BFZM10mBM7DJ2hkH8mCB8X5wm2FJHKaEzArR5Ljlx+rEuoe9b/zAq7kDTf0xCmB1iVB+YfK+bTZt1yP4815fzus=',
      'x-secsdk-csrf-token': '000100000001cef0bc6d28f2614ca76e7ec6a2825d3f471f27972ec0d6ee5c291e2703dfe29217ab66329c8c42da',
      'sec-ch-ua-mobile': '?0',
      'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
      'content-type': 'application/x-www-form-urlencoded;charset=UTF-8',
      'accept': 'application/json, text/plain, */*',
      'bd-ticket-guard-web-version': '1',
      'bd-ticket-guard-client-data': 'eyJ0c19zaWduIjoidHMuMS40MzM1MTkwYzRjN2ExYzUwZTk0NGYzNWJlNTc4NzZhNjA0YTdkYzRlZTk1NjBmMzk4YWE2NjRhYWVkNWE1NTY2YzRmYmU4N2QyMzE5Y2YwNTMxODYyNGNlZGExNDkxMWNhNDA2ZGVkYmViZWRkYjJlMzBmY2U4ZDRmYTAyNTc1ZCIsInJlcV9jb250ZW50IjoidGlja2V0LHBhdGgsdGltZXN0YW1wIiwicmVxX3NpZ24iOiJNRVFDSUN6NkFYUUJqMHN5b2ZweEJXcWVVUUh0VkRXWjNVSE4xWlFXZUhjbmNJQmpBaUI1cU11TlRhOUJiTmJ6RGJyWXdLYXpDcUd4cWhSem9nU01BakYzdkx1bTRnPT0iLCJ0aW1lc3RhbXAiOjE3MDU1NzAzOTB9',
      'sec-ch-ua-platform': '"macOS"',
      'origin': 'https://creator.douyin.com',
      'sec-fetch-site': 'same-origin',
      'sec-fetch-mode': 'cors',
      'sec-fetch-dest': 'empty',
      'referer': 'https://creator.douyin.com/creator-micro/content/publish?enter_from=publish_page',
      'accept-language': 'zh-CN,zh;q=0.9',
    };
    return defer(() =>
      axios.post(uri, data, { params, headers }),
    ).pipe(
      map(res => res.data),
    );
  }

  getTaskUploadAuth(task: DyUploadTask): DyUploadAuth {
    return JSON.parse(task.res_requestAuth.auth) as DyUploadAuth;
  }

  parseUploadNode(res: any): DyUploadRequestNode {
    const node = res.Result.InnerUploadAddress.UploadNodes[0];
    return {
      'Vid': node.Vid,
      'StoreUri': node.StoreInfos[0].StoreUri,
      'Auth': node.StoreInfos[0].Auth,
      'UploadID': node.StoreInfos[0].UploadID,
      'UploadHeader': node.StoreInfos[0].UploadHeader,
      'StorageHeader': node.StoreInfos[0].StorageHeader,
      'UploadHost': node.UploadHost,
      'SessionKey': node.SessionKey,
      'AdvanceOption': res.Result.InnerUploadAddress.AdvanceOption,
      'UploadUri': `https://${node.UploadHost}/upload/v1/${node.StoreInfos[0].StoreUri}`,
    };
  }

}